import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/api/odoo/finished_in_odoo_api.dart';
import 'package:flutter_admin/api/odoo/finished_in_scan_odoo_api.dart';
import 'package:flutter_admin/api/odoo/stock_move_line_odoo_api.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/models/odoo/finish_in.dart';
import 'package:flutter_admin/models/odoo/stock_move_line.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input_num.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/finish_in_scan.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter_admin/pages/odoo/product_productunitprice/product_list.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/eventbus.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:qrscan/qrscan.dart' as scanner;
import 'package:quiver/strings.dart';

class LocationInManual extends StatefulWidget {
  LocationInManual({Key? key,required this.locationList}) : super(key: key);

  final List<SelectOptionVO> locationList;

  @override
  _LocationInManualState createState() => _LocationInManualState();
}

class _LocationInManualState extends State<LocationInManual> {
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  StockMoveLine stockMoveLine = StockMoveLine();
  List<SelectOptionVO> pickingTypeList = [];
  List<SelectOptionVO> jobJsonList = [];
  List<SelectOptionVO> locationNextList = [];
  String? locationNextName;
  @override
  void initState() {
    super.initState();
    _loadOptionVO();
  }

  _loadOptionVO() async{
    ResponseBodyApi res = await StockMoveLineOdooApi.getPickingType("入库");
    if (res.success!){
      for(var i = 0; i < res.data.length; i++){
        pickingTypeList.add(SelectOptionVO(value: res.data[i]["id"].toString(),label: res.data[i]["name"]));
      }
    }
    if(widget.locationList.length == 1){
      stockMoveLine.locationId = widget.locationList[0].value.toString();
    }
    setState(() {});
  }

  @override
  void dispose() {
    super.dispose();
  }

  _getJobJson() async{
    if(!isBlank(stockMoveLine.jobType) && !isBlank(stockMoveLine.locationId)){
      jobJsonList = [];
      ResponseBodyApi res = await StockMoveLineOdooApi.getJobJson(
          typeId: stockMoveLine.jobType,
          scene: "入库",
          locationId: stockMoveLine.locationId
      );
      if (res.success!){
        for(var i = 0; i < res.data.length; i++){
          jobJsonList.add(SelectOptionVO(value: res.data[i].toString(),label: res.data[i]));
        }
      }
    }
  }

  //产品点击事件触发的方法
  _selectProduct() async {
    showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: ProductList(),
      ),
    ).then((v) {
      if (v != null) {
        //_query();
        formKey.currentState!.save();
        stockMoveLine.productName = v['name'];
        stockMoveLine.productCode = v['default_code'];
        stockMoveLine.productDesc = v['description'];
        stockMoveLine.productUomId = v['uom_id'][0].toString();
        stockMoveLine.productUomName = v['uom_id'][1].toString();
        setState(() {});
        _changeProductId(v['id']);
      }
    });
  }

  _changeProductId(productId) async{
    var res = await DynamicDataApi.getModels(model: 'product.product',key: 'product_tmpl_id',val: productId);
    if(res.success!){
      stockMoveLine.productId = res.data[0]['id'].toString();
    }
  }


  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CrySelect(
            label: '入库类型',
            dataList: pickingTypeList,
            value: stockMoveLine.jobType,
            onChange: (v) async {
              if (stockMoveLine.jobType != v) {
                formKey.currentState!.save();
                stockMoveLine.jobType = v;
                stockMoveLine.jobJson = null;
                try {
                  await _getJobJson();
                } catch (e) {
                  jobJsonList = [];
                }
                setState(() {});
              }
            },
            onSaved: (v) {
              stockMoveLine.jobType = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CryInput(
            label: '生产订单号',
            value: stockMoveLine.productionNo,
            onSaved: (v) {
              stockMoveLine.productionNo = v;
            },
          ),
          CrySelect(
            label: '入库库房',
            dataList: widget.locationList,
            value: stockMoveLine.locationId,
            onChange: (v) async {
              if (stockMoveLine.locationId != v) {
                formKey.currentState!.save();
                stockMoveLine.locationId = v;
                stockMoveLine.jobJson = null;
                try {
                  await _getJobJson();
                  locationNextList = await DynamicDataApi.getModelSelect(
                      model: 'stock.location',
                      name: 'complete_name',
                      // tag: "complete_name",
                      key: 'father_locaiton',
                      val: int.parse(stockMoveLine.locationId!)
                  );
                } catch (e) {
                  // jobJsonList = [];
                }
                setState(() {});
              }
            },
            onSaved: (v) {
              stockMoveLine.locationId = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CrySelect(
            label: '发方位置',
            dataList: jobJsonList,
            value: stockMoveLine.jobJson,
            onSaved: (v) {
              stockMoveLine.jobJson = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CrySelect(
            label: '库位',
            dataList: locationNextList,
            value: stockMoveLine.shelves,
            onSaved: (v) {
              stockMoveLine.shelves = v;
            },
          ),
          CryInput(
            label: '物料名称',
            value: stockMoveLine.productName,
            onSaved: (v) {
              stockMoveLine.productName = v;
            },
            onTap: () => _selectProduct(),
            validator: (v) {
              return v!.isEmpty ? "请选择物料" : null;
            },
          ),
          CryInput(
            label: '物料编码',
            enable: false,
            value: stockMoveLine.productCode,
            onSaved: (v) {
              stockMoveLine.productCode = v;
            },
          ),
          CryInput(
            label: '规格型号',
            enable: false,
            value: stockMoveLine.productDesc,
            onSaved: (v) {
              stockMoveLine.productDesc = v;
            },
          ),
          CryInputNum(
            label: '数量',
            value: stockMoveLine.qtyDone,
            onSaved: (v) {
              stockMoveLine.qtyDone = v;
            },
            validator: (v) {
              return v!.isEmpty ? "请输入数量" :num.parse(v) ==0? "数量不可以为0": null;
            },
          ),
          CryInput(
            label: '单位',
            enable: false,
            value: stockMoveLine.productUomName,
            onSaved: (v) {
              stockMoveLine.productUomName = v;
            },
          ),
          CryInput(
            label: '备注',
            value: stockMoveLine.remark,
            onSaved: (v) {
              stockMoveLine.remark = v;
            },
          ),
        ],
      ),
    );

    var footerBar = ButtonBar(
      alignment: MainAxisAlignment.center,
      children: <Widget>[
        CryButton(
          label: "确定",
          onPressed: () {
            FormState form = formKey.currentState!;
            if (!form.validate()) {
              return;
            }
            form.save();
            StockMoveLineOdooApi.inCreate(stockMoveLine.toOdooMap()).then((ResponseBodyApi res) {
              if (!res.success!) {
                return;
              }
              Navigator.pop(context, true);
              CryUtils.message(S.of(context).saved);
            });
          },
          iconData: Icons.save,
        ),
        CryButton(
          label: S.of(context).cancel,
          onPressed: () {
            Navigator.pop(context);
          },
          iconData: Icons.cancel,
        )
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      appBar: AppBar(
        title: Text("手动入库"),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [form],
        ),
      ),
      bottomNavigationBar: footerBar,
    );
    return SizedBox(
      width: 650,
      height: 650,
      child: result,
    );
  }


  // _loadData() async {
  //   print(finishedInScan.productorderno);
  //   var finishedInScanToOdoo = [
  //     if (finishedInScan.productorderno != null &&
  //         finishedInScan.productorderno != '')
  //       ['name', '=', finishedInScan.productorderno],
  //     if (finishedInScan.productCode != null &&
  //         finishedInScan.productCode != '')
  //       [
  //         'product_id.product_tmpl_id.default_code',
  //         '=',
  //         finishedInScan.productCode
  //       ],
  //   ];
  //   ResponseBodyApi responseBodyApi = await FinishedInScanOdooApi.page(
  //       data: {"domainList": finishedInScanToOdoo});
  //   if (responseBodyApi.success!) {
  //     tableList = responseBodyApi.data;
  //     setState(() {});
  //   }
  // }

}
